import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import api from '../../services/api';
import './RegisterPage.css';

function RegisterPage() {
    const navigate = useNavigate();
    const [formData, setFormData] = useState({
        username: '',
        email: '',
        password: '',
        vertificationCode: '',
        invitationCode: '',
        bio: '',
        age: '',
        school: '',
        college: ''
    });
    const [avatar, setAvatar] = useState(null);
    const [showPassword, setShowPassword] = useState(false);
    const [loading, setLoading] = useState(false);
    const [verifyLoading, setVerifyLoading] = useState(false);
    const [message, setMessage] = useState({ type: '', text: '' });

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
    };

    const handleAvatarChange = (e) => {
        const file = e.target.files[0];
        if (file) {
            setAvatar(file);
        }
    };

    const handleGetVerifyCode = async () => {
        if (!formData.username || !formData.email) {
            setMessage({ type: 'error', text: '请先填写用户名和邮箱' });
            return;
        }

        setVerifyLoading(true);
        try {
            const result = await api.getVerifyCode(formData.username, formData.email, 0);
            if (result.code === 200) {
                setMessage({ type: 'success', text: '验证码已发送到您的邮箱' });
            } else {
                //setMessage({ type: 'error', text: result.message || '发送验证码失败' });
            }
        } catch (error) {
            //setMessage({ type: 'error', text: '发送验证码失败' });
        } finally {
            setVerifyLoading(false);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!formData.username || !formData.email || !formData.password ||
            !formData.vertificationCode || !formData.invitationCode) {
            setMessage({ type: 'error', text: '请填写所有必填字段' });
            return;
        }

        setLoading(true);
        try {
            // 准备FormData
            const submitFormData = new FormData();

            // 准备metadata对象
            const metadata = {
                username: formData.username,
                email: formData.email,
                password: formData.password,
                vertificationCode: formData.vertificationCode,
                invitationCode: formData.invitationCode,
                bio: formData.bio,
                age: formData.age ? parseInt(formData.age) : undefined,
                school: formData.school,
                college: formData.college
            };

            // 创建带有正确Content-Type的Blob
            const metadataBlob = new Blob([JSON.stringify(metadata)], {
                type: 'application/json'
            });

            submitFormData.append('metadata', metadataBlob);

            if (avatar) {
                submitFormData.append('avatar', avatar);
            }

            const result = await api.register(submitFormData);
            setMessage({ type: 'success', text: '注册成功，请登录' });
            setTimeout(() => {
                navigate('/login');
            }, 2000);
        } catch (error) {
            setMessage({ type: 'error', text: error.message || '注册失败' });
        } finally {
            setLoading(false);
        }
    };
    return (
        <div className="register-container">
            <div className="register-form-container card">
                <div className="register-title card-header">
                    <h1 className="card-title">用户注册</h1>
                    <p className="card-subtitle">加入PT站大家庭</p>
                </div>

                {message.text && (
                    <div className={`message ${message.type}`}>
                        {message.text}
                    </div>
                )}

                <form onSubmit={handleSubmit} className="register-form">
                    <div className="form-row">
                        <div className="form-group">
                            <label className="form-label">
                                👤 用户名 *
                            </label>
                            <input
                                type="text"
                                name="username"
                                value={formData.username}
                                onChange={handleInputChange}
                                className="form-input"
                                placeholder="请输入用户名"
                                required
                            />
                        </div>

                        <div className="form-group">
                            <label className="form-label">
                                📧 邮箱 *
                            </label>
                            <input
                                type="email"
                                name="email"
                                value={formData.email}
                                onChange={handleInputChange}
                                className="form-input"
                                placeholder="请输入邮箱地址"
                                required
                            />
                        </div>
                    </div>

                    <div className="form-group">
                        <label className="form-label">
                            🔒 密码 *
                        </label>
                        <div className="password-container">
                            <input
                                type={showPassword ? 'text' : 'password'}
                                name="password"
                                value={formData.password}
                                onChange={handleInputChange}
                                className="form-input"
                                placeholder="请输入密码"
                                required
                            />
                            <button
                                type="button"
                                onClick={() => setShowPassword(!showPassword)}
                                className="password-toggle"
                            >
                                {showPassword ? '🙈' : '👁️'}
                            </button>
                        </div>
                    </div>

                    <div className="form-row">
                        <div className="form-group">
                            <label className="form-label">
                                🔑 验证码 *
                            </label>
                            <div className="verify-group">
                                <input
                                    type="text"
                                    name="vertificationCode"
                                    value={formData.vertificationCode}
                                    onChange={handleInputChange}
                                    className="form-input verify-input"
                                    placeholder="验证码"
                                    required
                                />
                                <button
                                    type="button"
                                    onClick={handleGetVerifyCode}
                                    disabled={verifyLoading}
                                    className="verify-btn"
                                >
                                    {verifyLoading ? '发送中' : '获取'}
                                </button>
                            </div>
                        </div>

                        <div className="form-group">
                            <label className="form-label">
                                🎫 邀请码 *
                            </label>
                            <input
                                type="text"
                                name="invitationCode"
                                value={formData.invitationCode}
                                onChange={handleInputChange}
                                className="form-input"
                                placeholder="请输入邀请码"
                                required
                            />
                        </div>
                    </div>

                    <div className="form-group">
                        <label className="form-label">
                            📷 头像
                        </label>
                        <input
                            type="file"
                            accept="image/*"
                            onChange={handleAvatarChange}
                            className="file-input"
                        />
                    </div>

                    <div className="form-row">
                        <div className="form-group">
                            <label className="form-label">
                                📅 年龄
                            </label>
                            <input
                                type="number"
                                name="age"
                                value={formData.age}
                                onChange={handleInputChange}
                                className="form-input"
                                placeholder="请输入年龄"
                            />
                        </div>

                        <div className="form-group">
                            <label className="form-label">
                                🏫 学校
                            </label>
                            <input
                                type="text"
                                name="school"
                                value={formData.school}
                                onChange={handleInputChange}
                                className="form-input"
                                placeholder="请输入学校名称"
                            />
                        </div>
                    </div>

                    <div className="form-group">
                        <label className="form-label">
                            📚 学院
                        </label>
                        <input
                            type="text"
                            name="college"
                            value={formData.college}
                            onChange={handleInputChange}
                            className="form-input"
                            placeholder="请输入学院名称"
                        />
                    </div>

                    <div className="form-group">
                        <label className="form-label">
                            📝 个人简介
                        </label>
                        <textarea
                            name="bio"
                            value={formData.bio}
                            onChange={handleInputChange}
                            className="form-input form-textarea"
                            placeholder="介绍一下自己吧..."
                        />
                    </div>

                    <button
                        type="submit"
                        disabled={loading}
                        className="btn btn-full"
                    >
                        {loading ? '注册中...' : '注册'}
                    </button>
                </form>

                <div className="register-footer">
                    <p>
                        已有账号？
                        <Link to="/login" className="form-link">
                            立即登录
                        </Link>
                    </p>
                </div>
            </div>
        </div>
    );
}

export default RegisterPage;